package br.com.myuni.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.myuni.ConnectionFactory;
import br.com.myuni.modelo.Grade;

public class GradeDaoImpl implements GradeDao {
	
	//comentario jrt
	Connection connection;
	//comentario dk
	
	public GradeDaoImpl(){
		this.connection = new ConnectionFactory().getConnection();
	}

	@Override
	public void adiciona(Grade grade){
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("myUniEM");
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		em.persist(grade);
		em.getTransaction().commit();
		
		System.out.println("ID da Grade: "+ grade.getId_grade());
		
		em.close();
	}
	
	

	@Override
	public List<Grade> getLista() {
		
		try{
			List<Grade> grades = new ArrayList<Grade>();
			
			PreparedStatement stmt = connection.
						prepareStatement("SELECT * FROM UNI_grade");
			ResultSet rs = stmt.executeQuery();
			
			while(rs.next()){
				//criando objeto Grade
				Grade grade = new Grade();
				
				grade.setId_grade(rs.getInt("id_grade"));
				grade.setNm_grade(rs.getString("nm_grade"));
				
				grades.add(grade);
			}
			
			rs.close();
			stmt.close();
			
			return grades;
		}catch(SQLException e){
			throw new RuntimeException(e);
		}		
	}

}
